﻿using BeetleX.Buffers;
using BeetleX.Clients;
using System;
using System.IO;

#nullable disable
namespace BeetleX.XRPC.Packets
{
    public class ClientPacket : IClientPacket, IDisposable
    {
        private RPCPacket mPacket;

        public Options Options { get; set; }

        public EventClientPacketCompleted Completed { get; set; }

        public IClientPacket Clone()
        {
            return new ClientPacket()
            {
                Options = this.Options
            };
        }

        public void Decode(IClient client, Stream stream)
        {
            PipeStream pipeStream = stream.ToPipeStream();
            while (true)
            {
                if (this.mPacket == null)
                {
                    this.mPacket = new RPCPacket();
                    this.mPacket.Client = (AsyncTcpClient)client;
                }
                if (this.mPacket.Read(this.Options, pipeStream))
                {
                    try
                    {
                        EventClientPacketCompleted completed = this.Completed;
                        if (completed != null)
                            completed(client, this.mPacket);
                    }
                    finally
                    {
                        //mPacket?.Dispose();
                        mPacket = null;
                    }
                }
                else
                    break;
            }
        }

        public void Dispose()
        {
            mPacket?.Dispose();
        }

        public void Encode(object data, IClient client, Stream stream)
        {
            PipeStream pipeStream = stream.ToPipeStream();
            (data as RPCPacket).Write(this.Options, pipeStream);
        }
    }
}
